package com.example.demo.controller;

import com.example.demo.core.Result;
import com.example.demo.entity.Banner;
import com.example.demo.pojo.request.CreateOrUpdateBannerRequest;
import com.example.demo.service.BannerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 轮播图控制器
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@Tag(name = "轮播图管理", description = "轮播图管理")
@RestController
@RequestMapping("/banner")
@RequiredArgsConstructor
public class BannerController {

    private final BannerService bannerService;

    /**
     * 获取全部的轮播图列表
     *
     * @return API全局响应对象
     */
    @Operation(summary = "获取轮播图列表")
    @GetMapping
    public Result<List<Banner>> getBannerList() {
        List<Banner> bannerList = bannerService.getAllBanner();
        return Result.ok(bannerList);
    }

    /**
     * 添加新的轮播图
     *
     * @param createBanner 添加的轮播图信息
     * @return API全局响应对象
     */
    @Operation(summary = "添加新的轮播图")
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('/banner/create')")
    public Result<Void> createBanner(@RequestBody @Validated CreateOrUpdateBannerRequest createBanner) {
        Banner banner = new Banner();
        BeanUtils.copyProperties(createBanner, banner);
        bannerService.create(banner);
        return Result.ok();
    }

    /**
     * 根据轮播图ID删除录播图信息
     *
     * @param id 轮播图ID
     * @return API全局响应对象
     */
    @Operation(summary = "删除轮播图")
    @PostMapping("/{id}/delete")
    @PreAuthorize("hasAuthority('/banner/delete')")
    public Result<Void> deleteBannerById(@PathVariable("id") Long id) {
        bannerService.deleteById(id);
        return Result.ok();
    }

    /**
     * 根据轮播图ID更新录播图信息
     *
     * @param id           轮播图ID
     * @param updateBanner 待更新的轮播图信息
     * @return API全局响应对象
     */
    @Operation(summary = "更新轮播图")
    @PostMapping("/{id}/update")
    @PreAuthorize("hasAuthority('/banner/update')")
    public Result<Void> updateBannerById(@PathVariable("id") Long id,
                                         @RequestBody @Validated CreateOrUpdateBannerRequest updateBanner) {
        Banner banner = new Banner();
        BeanUtils.copyProperties(updateBanner, banner);
        bannerService.updateById(id, banner);
        return Result.ok();
    }
}
